//
//  ICRedPacketReceiveView.m
//  ICome
//
//  Created by 席鹏飞 on 2016/11/8.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICRedPacketReceiveView.h"
#import "ICHeadImageView.h"
#import "NSMutableAttributedString+Extension.h"
#import "UIImage+AvatarGeneration.h"

#define ImageHeight 45
#define LineWidth 3

@interface ICRedPacketReceiveView()
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) ICHeadImageView *headerImageView;  // 头像
@property (nonatomic, strong) UILabel *nameLabel; // 姓名
@property (nonatomic, strong) UIImageView *redPacketImage;
@property (nonatomic, strong) UIImageView *openImageView; // 启
@property (nonatomic, strong) UILabel *promptLabel; // 提示
@property (nonatomic, strong) UILabel *wishLabel; // 节节高升
@property (nonatomic, strong) UIButton *seeAllButton; // 看看大家
@property (nonatomic, assign) KReceiveState receiveState;
@end

@implementation ICRedPacketReceiveView

- (instancetype)initWithState:(KReceiveState)state
                 messageModel:(ICMessageModel *)messageModel {
    
    self = [super init];
    if (self) {
        self.receiveState = state;
        self.frame = App_RootCtr.view.frame;
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        [self reSetBgImageViewFrame];
        
        WEAKSELF;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf startRotation];
            if ([weakSelf.delegate respondsToSelector:@selector(openImageClicked)]) {
                [weakSelf.delegate openImageClicked];
            }
        }];
        [self.openImageView addGestureRecognizer:tap];

        NSString *photoId = [ICMessageDatabase getPhotoIdWithEId:messageModel.message.from];
        NSString *name = [ICMessageDatabase getUserNameWithEId:messageModel.message.from];
        NSString *URL = [ICTools getMinImageURL:(photoId)];
        [UIImage addAvatariamgeView:self.headerImageView.imageView withUrlStr:URL witheId:messageModel.message.from withName:name];
        self.nameLabel.text = name;
    }
    return self;
}

- (void)startRotation {
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];
    //旋转角度
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI];
    //每次旋转的时间（单位秒）
    rotationAnimation.duration = 0.5;
    rotationAnimation.cumulative = YES;
    //重复旋转的次数
    rotationAnimation.repeatCount = MAXFLOAT;
    [self.openImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

- (void)reSetBgImageViewFrame {
    CGRect rect = self.bgImageView.frame;
    rect.size.width = APP_Frame_Height / 667.0 * rect.size.width;
    rect.size.height = App_Frame_Width / 375.0 * rect.size.height;
    rect.origin.x = (App_Frame_Width - rect.size.width)/2;
    rect.origin.y = (APP_Frame_Height - rect.size.height)/2;
    self.bgImageView.frame = rect;
}

- (void)setReceiveStateForView {
    /** 单人红包已过期 || 群组红包已过期 */
    if (self.receiveState == KReceiveState_single_overdue || self.receiveState == KReceiveState_group_overdue) {
        self.openImageView.hidden = YES;
        self.wishLabel.hidden = YES;
        NSMutableAttributedString *string = [NSMutableAttributedString attributedString:@[self.promptString, @"“我的红包”", @"中查看"] colors:@[ICRGB(0xff9288), ICRGB(0xdecd98), ICRGB(0xff9288)] fonts:@[[UIFont systemFontOfSize:14], [UIFont systemFontOfSize:14], [UIFont systemFontOfSize:14]]];
        [string setAlignment:NSTextAlignmentCenter];
        [string setLineSpacing:5.0];
        self.promptLabel.attributedText = string;
        if (self.receiveState == KReceiveState_single_overdue) {
            self.seeAllButton.hidden = YES;
        }
    }
    /** 单人红包未过期未领取 || 群组红包未过期可以抢 */
    else if (self.receiveState == KReceiveState_single_noGet || self.receiveState == KReceiveState_group_canGet) {
        self.promptLabel.hidden = YES;
        if (self.receiveState == KReceiveState_single_noGet) {
            self.seeAllButton.hidden = YES;
        }
    }
    /** 群组红包未过期被抢光 */
    else if (self.receiveState == KReceiveState_group_noGet) {
        self.openImageView.hidden = YES;
        self.wishLabel.hidden = YES;
        self.promptLabel.attributedText = [NSMutableAttributedString attributedString:@[@"手慢了，红包已经被抢光了..."] colors:@[ICRGB(0xff9288)] fonts:@[[UIFont systemFontOfSize:14]]];
    }
}

- (void)closeRedPacketReceiveView {
    [self.bgImageView removeFromSuperview];
    [self removeFromSuperview];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.closeButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bgImageView.mas_left);
        make.top.equalTo(self.bgImageView.mas_top);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(50);
    }];
    [self.headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgImageView.mas_centerX);
        make.top.equalTo(self.bgImageView.mas_top).offset(APP_Frame_Height > 568 ? 45 : 25);
        make.width.mas_equalTo(ImageHeight);
        make.height.mas_equalTo(ImageHeight);
    }];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgImageView.mas_centerX);
        make.top.equalTo(self.headerImageView.mas_bottom).offset(8);
        make.height.mas_equalTo(20);
    }];
    [self.redPacketImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgImageView.mas_centerX);
        make.top.equalTo(self.nameLabel.mas_bottom).offset(3);
    }];
    [self.openImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgImageView.mas_centerX);
        make.centerY.equalTo(self.bgImageView.mas_centerY);
    }];
    [self.promptLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgImageView.mas_centerX);
        make.top.mas_equalTo(self.bgImageView.height/2 + 45);
        make.left.equalTo(self.bgImageView.mas_left).offset(10);
        make.right.equalTo(self.bgImageView.mas_right).offset(-10);
    }];
    [self.wishLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgImageView.mas_centerX);
        make.top.equalTo(self.openImageView.mas_bottom);
        make.bottom.equalTo(self.bgImageView.mas_bottom).offset(-30);
    }];
    [self.seeAllButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bgImageView.mas_centerX);
        make.bottom.equalTo(self.bgImageView.mas_bottom);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(60);
    }];
}

- (void)addAnimationEffect {
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseInOut animations:^{
        self.layer.transformScale = 1.2;
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseInOut animations:^{
            self.layer.transformScale = 1.0;
        }completion:^(BOOL finished) {
            
        }];
    }];
}

- (void)addMyRedPacketTapGesture {
    if ([self.promptLabel.text containsString:@"我的红包"]) {
        WEAKSELF;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            if ([weakSelf.delegate respondsToSelector:@selector(myRedPacketClicked)]) {
                [weakSelf closeRedPacketReceiveView];
                [weakSelf.delegate myRedPacketClicked];
            }
        }];
        [self.promptLabel addGestureRecognizer:tap];
    }
}

- (void)showInView:(UIView *)view {
    [self setReceiveStateForView];
    [self addMyRedPacketTapGesture];
    [view addSubview:self];
    [self addAnimationEffect];
}

#pragma mark - Event response

- (void)closeBtnClicked:(id)sender {
    [self closeRedPacketReceiveView];
}

- (void)seeAllBtnClicked:(id)sender {
    if ([self.delegate respondsToSelector:@selector(seeAllBtnClicked)]) {
        [self closeRedPacketReceiveView];
        [self.delegate seeAllBtnClicked];
    }
}

#pragma mark - Getter

- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 290, 410)];
        _bgImageView.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_receive_bg"];
        _bgImageView.userInteractionEnabled = YES;
        [self addSubview:_bgImageView];
    }
    return _bgImageView;
}

- (UIButton *)closeButton {
    if (!_closeButton) {
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_close"] forState:UIControlStateNormal];
        [_closeButton addTarget:self action:@selector(closeBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.bgImageView addSubview:_closeButton];
    }
    return _closeButton;
}

- (ICHeadImageView *)headerImageView {
    if (!_headerImageView) {
        _headerImageView = [[ICHeadImageView alloc] init];
        [self.bgImageView addSubview:_headerImageView];
    }
    return _headerImageView;
}

- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.textColor = ICRGB(0xfd8e85);
        _nameLabel.font = [UIFont systemFontOfSize:14];
        [self.bgImageView addSubview:_nameLabel];
    }
    return _nameLabel;
}

- (UIImageView *)redPacketImage {
    if (!_redPacketImage) {
        _redPacketImage = [[UIImageView alloc] init];
        _redPacketImage.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_receive"];
        [self.bgImageView addSubview:_redPacketImage];
    }
    return _redPacketImage;
}

- (UIImageView *)openImageView {
    if (!_openImageView) {
        _openImageView = [[UIImageView alloc] init];
        _openImageView.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_open"];
        _openImageView.userInteractionEnabled = YES;
        [self.bgImageView addSubview:_openImageView];
    }
    return _openImageView;
}

- (UILabel *)promptLabel {
    if (!_promptLabel) {
        _promptLabel = [[UILabel alloc] init];
        _promptLabel.numberOfLines = 0;
        _promptLabel.textAlignment = NSTextAlignmentCenter;
        _promptLabel.userInteractionEnabled = YES;
        [self.bgImageView addSubview:_promptLabel];
    }
    return _promptLabel;
}

- (UILabel *)wishLabel {
    if (!_wishLabel) {
        _wishLabel = [[UILabel alloc] init];
        _wishLabel.textColor = ICRGB(0xeef19e);
        _wishLabel.font = ICFont(18.0 * Level);
        _wishLabel.text = @"节节高升，再创佳绩!";
        _wishLabel.userInteractionEnabled = NO;
        [self.bgImageView addSubview:_wishLabel];
    }
    return _wishLabel;
}

- (UIButton *)seeAllButton {
    if (!_seeAllButton) {
        _seeAllButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_seeAllButton setTitle:@"看看大家" forState:UIControlStateNormal];
        [_seeAllButton setTitleColor:ICRGB(0x759cde) forState:UIControlStateNormal];
        _seeAllButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_seeAllButton addTarget:self action:@selector(seeAllBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.bgImageView addSubview:_seeAllButton];
    }
    return _seeAllButton;
}

@end
